package com.liuyi.framework.web.note;

import cn.hutool.core.util.StrUtil;
import com.liuyi.tools.kits.RequestKit;
import com.liuyi.tools.web.resp.ResponseCall;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * 短信验证拦截器
 * </p>
 *
 * @author Mr.Fmy
 * @since 2020-12-12
 */
@Slf4j
public class NoteValitionHandler implements HandlerInterceptor {

    @Resource
    private NoteUrlStorage urlStorage;
    @Resource
    private NoteStorageValition storageValition;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        NoteUrl url = urlStorage.getUrl(request.getRequestURI());
        if (url == null) {
            //如果没有验证，直接通过
            return true;
        }
        String phone = storageValition.getPhone(url, request);
        String noteCode = storageValition.getNoteCode(request);
        String valitionCode = storageValition.get(url.getType(), phone);
        String errMsg = "";
        //验证
        if (StrUtil.isBlank(phone)) {
            errMsg = "请输入手机号";
        } else if (StrUtil.isBlank(noteCode)) {
            errMsg = "请输入验证码";
        } else if (StrUtil.isBlank(valitionCode)) {
            errMsg = "验证码已过期或不存在";
        } else if (!valitionCode.equals(noteCode)) {
            errMsg = "验证码错误";
            //获取当前试错次数
            if (storageValition.getValitonMaxCount() <= (storageValition.getValitionCount(url, phone) - 1)) {
                //试错过多，删除该验证码
                storageValition.remove(url.getType(), phone);
            } else {
                //储存验证失败信息
                storageValition.setValitonFail(url, phone);
            }
        } else {
            //验证成功，移除
            storageValition.remove(url.getType(), phone);
        }

        //如果存在异常，就返回
        if (StrUtil.isNotBlank(errMsg)) {
            //返回异常
            try {
                RequestKit.responseWriter(response, HttpStatus.OK, ResponseCall.error(errMsg));
                return false;
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                return false;
            }
        }
        return true;
    }
}
